<?php
/**
 * CK框架 MYSQL类
 * @author wujibing<283109896@qq.com>
 * @version   3.0
 * @category   CkFrameWork
 * @package  CkFrameWork
 * @subpackage db
 */
class mysql_db implements IDb_db
{

	/**
	 * 当前连接对象
	 * @var Resource
	 */
	private $nowConn;

	private $queryResource;
	

	/**
	 * 初始化数据库
	 * @param Array $config
	 * @throws base_base_Exception
	 */
	public function __construct ($config)
	{
	    if(!$config->HOST)
	    {
	        throw new base_Exception(lang::getLang('__NOW_DB_NOT_HOST__'));    
	    }
		$func = $config->PCONNECT ? 'mysql_pconnect' : 'mysql_connect';
		$host = $config->HOST .(isset($config->PORT) ? ':' . $config->PORT : '');
		$this->nowConn = $func($host, $config->USERNAME, $config->PASSWORD);
		if (! $this->nowConn)
		{
			throw new base_Exception(lang::getLang('__CONNECT_DB_ERROR__',array(mysql_error())), __LINE__);
		}
		$version = mysql_get_server_info($this->nowConn);
		if ($version >= "4.1")
		{
			//使用UTF8存取数据库 需要mysql 4.1.0以上支持
			mysql_query('SET NAMES \'' . $config->CHARSET . '\'', $this->nowConn);
		}
		//设置 sql_model
		if ($version > '5.0.1')
		{
			mysql_query('SET sql_mode=\'\'', $this->nowConn);
		}
		$this->selectDb($config->DBNAME);
	}

	/**
	 * 选择数据库
	 * @param string $dbName
	 * @return boolean
	 */
	public function selectDb ($dbName)
	{
		if (! mysql_select_db($dbName, $this->nowConn))
		{
			throw new base_Exception(lang::getLang('__CHANGE_DB_ERROR__',array(mysql_error())), __LINE__);
		}
	}

	/**
	 * (non-PHPdoc)
	 * @see IDb_db::insert()
	 */
	public function insert ($sql)
	{
		return $this->mysqlQuery($sql, dbQueryType::insert);
	}

	/**
	 * (non-PHPdoc)
	 * @see IDb_db::update()
	 */
	public function update ($sql)
	{
		return $this->mysqlQuery($sql, dbQueryType::update);
	}

	/**
	 * (non-PHPdoc)
	 * @see IDb_db::delete()
	 */
	public function delete ($sql)
	{
		return $this->mysqlQuery($sql, dbQueryType::delete);
	}

	/**
	 * 查询数据库
	 * (non-PHPdoc)
	 * @see IDb_db::query()
	 */
	public function query ($sql,$key='')
	{
		if (is_resource($this->queryResource))
		{
			$this->free();
		}
		//echo $sql.'<br>';
		$this->mysqlQuery($sql, dbQueryType::query);
		$result = array();
		while (($r = mysql_fetch_array($this->queryResource, MYSQL_ASSOC)) == true)
		{
			!$key ? $result[] = $r : $result[$r[$key]] = $r;
		}
		return $result;
	}
	/**
	 * (non-PHPdoc)
	 * @see IDb_db::count()
	 */
	public function count($sql)
	{
		$result = $this->query($sql);
		return $result[0]['count'];
	}

	/**
	 * (non-PHPdoc)
	 * @see IDb_db::getInsertId()
	 */
	public function getInsertId ()
	{
		return mysql_insert_id($this->nowConn);
	}

	/**
	 * (non-PHPdoc)
	 * @see IDb_db::beginTransaction()
	 */
	public function beginTransaction ()
	{
		mysql_query('START TRANSACTION', $this->nowConn);
	}

	/**
	 * (non-PHPdoc)
	 * @see IDb_db::commit()
	 */
	public function commit ()
	{
		mysql_query('COMMIT', $this->nowConn);
	}

	/**
	 * (non-PHPdoc)
	 * @see IDb_db::rollBack()
	 */
	public function rollBack ()
	{
		mysql_query('ROLLBACK', $this->nowConn);
	}

	/**
	 * (non-PHPdoc)
	 * @see IDb_db::getDbType()
	 */
	public function getDbType ()
	{
		return 'mysql';
	}
	public function getFields($tableName)
	{
		$result = $this->query('show columns from '.$tableName.'');
		$info   = array();
		if($result)
		{
			foreach ($result as $key => $val)
			{
				$info[$val['Field']] = array
				(
						'type'    => $val['Type'],
						'notnull' => (bool) ($val['Null'] === ''), // not null is empty, null is yes
						'default' => $val['Default'],
						'primary' => (strtolower($val['Key']) == 'pri'),
						'autoinc' => (strtolower($val['Extra']) == 'auto_increment'),
				);
			}
		}
		return $info;
	}
	/**
	 * 释放
	 */
	private function free ()
	{
		mysql_free_result($this->queryResource);
	}

	private function mysqlQuery ($sql, $dbQueryType)
	{
		$this->queryResource = mysql_query($sql, $this->nowConn);
		//echo $sql.'<br>';
		if ($this->queryResource == false)
		{
			throw new queryFaild_sql_Exception($dbQueryType, $sql, mysql_error($this->nowConn), mysql_errno($this->nowConn));
			return false;
		}
		return true;
	}

	public function __destruct ()
	{
		if ($this->nowConn)
		{
			mysql_close($this->nowConn);
		}
	}
}